import fs from 'fs'
import crypto from 'crypto'
// import images from 'images'
import { RESOURCES_PATH, STATIC_PATH, IMAGE_TYPE } from './config'
import Jimp from 'jimp'
import gm from 'gm'

// 格式化时间戳
export const parseTime = (time: number | string| Date, cFormat = '{y}-{m}-{d} {h}:{i}:{s}'): string => {
  if (!time) return ''

  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        time = parseInt(time)
      } else {
        time = time.replace(/-/gm, '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return timeStr
}

// 获取文件后缀
export const getSuffix = (fileName = '') => {
  return fileName.includes('.') ? fileName.substr(fileName.lastIndexOf('.') + 1) : ''
}

// 获取文件名称
export const getFileName = (fileName = '') => {
  return fileName.includes('.') ? fileName.substr(0, fileName.lastIndexOf('.')) : fileName
}

// 检查文件夹是否存在再创建文件夹
export const mkdirCheckExists = (path = '') => {
  if (!path) return

  if (!fs.existsSync(path)) {
    fs.mkdirSync(path)
  }
}

// MD5 加密
export const md5 = (val = '') => crypto.createHash('md5').update(val, 'utf-8').digest('hex')

export const saveExtraImage = async (file: string) => {
  const filename =  getFileName(file)
  const suffix =  getSuffix(file)

  // 水印距离右下角百分比
  const LOGO_MARGIN_PERCENTAGE = 1 / 100
  
  const [sourceImg, waterLogo] = await Promise.all([
    Jimp.read(RESOURCES_PATH + file),
    Jimp.read(STATIC_PATH + 'water-logo.png'),
  ])

  waterLogo.scale(sourceImg.bitmap.width / waterLogo.bitmap.width / 3)

  const xMargin = sourceImg.bitmap.width * LOGO_MARGIN_PERCENTAGE;
  const yMargin = sourceImg.bitmap.width * LOGO_MARGIN_PERCENTAGE;
  const X = sourceImg.bitmap.width - waterLogo.bitmap.width - xMargin;
  const Y = sourceImg.bitmap.height - waterLogo.bitmap.height - yMargin;

  const result = await sourceImg.composite(waterLogo, X, Y, {
    mode: Jimp.BLEND_SOURCE_OVER,
    opacitySource: 0.8,
    opacityDest: 1
  })

  // 生成水印图
  result.write(RESOURCES_PATH + filename + `_${IMAGE_TYPE.LOGO}.` + suffix)

  // 生成缩略图
  gm(RESOURCES_PATH + file)
    .resize(sourceImg.bitmap.width / 2, sourceImg.bitmap.height / 2)
    .quality(50)
    .write(RESOURCES_PATH + filename + `_${IMAGE_TYPE.THUMBNAIL}.` + suffix, function(err) {
      err && console.log(err)
    })
}